#coding:utf-8
'''
create on 2017-05-31

@author: sandy
'''

import logging
from twisted.internet import reactor, defer
from twisted.web.client import Agent, readBody
from twisted.web.http_headers import Headers
from twisted.web.iweb import IBodyProducer
from zope.interface import implements
import json
import WeChatConfig
import ClientFactory
from pycommon import Pack as packet
from pycommon import Const,Utils
import GameDb


class StringProducer(object):
    implements(IBodyProducer)
 
    def __init__(self, body):
        self.body = body
        self.length = len(body)
 
    def startProducing(self, consumer):
        consumer.write(self.body)
        return defer.succeed(None)
 
    def pauseProducing(self):
        pass
 
    def stopProducing(self):
        pass


class WeChatGate(object):
    def __init__(self):
        pass

    def cbRequest(self,response, pid,wxcode):
        logging.debug(u"cbRequest WeChat response.code=%d pid = %d wxcode=%s", response.code, pid ,wxcode)
        d = readBody(response)
        d.addCallback(self.cbBody, pid, wxcode)
        return d
    
    def cbBody(self,body,pid, wxcode):
        body = body.decode(WeChatConfig.ENCODING)
        jf = json.loads(body)
        logging.info(u"cbBody WeChat pid = %d wxcode = %s body = %s",pid,wxcode,jf)
        #access_token openid unionid
        data = u'access_token=%s&openid=%s' % (jf.get("access_token"),jf.get("openid"))
        url = WeChatConfig.USER_INFO.encode(WeChatConfig.ENCODING) + data.encode(WeChatConfig.ENCODING)
        logging.debug(u"WX USERINFO url=%s",url)
        agent = Agent(reactor)
        d = agent.request("GET",url,Headers({'Content-Type':['application/x-www-form-urlencoded']}))
        d.addCallback(self.userInfoRequest,pid,wxcode)
        return d

    def userInfoRequest(self,response, pid,wxcode):
        logging.debug(u"userInfoRequest WeChat response.code=%d", response.code)
        d = readBody(response)
        d.addCallback(self.userInfoCbk, pid, wxcode)
        return d     

    def userInfoCbk(self,body,pid,wxcode):
        body = body.decode(WeChatConfig.ENCODING)
        jf = json.loads(body)
        logging.info(u"userInfoCbk WeChat pid = %d wxcode = %s body = %s",pid,wxcode,jf)
        # headimgurl sex nickname openid unionid
        c = ClientFactory.instance.getProtocol(pid)
        if c:
            nickname = jf.get("nickname")
            headimgurl = jf.get("headimgurl")
            sex = jf.get("sex")
            openid = jf.get("openid")
            unionid = jf.get("unionid")
            #c.sendPacket(packet.pack("HsSB",Const.CMD_L2C_WX_LOGIN,Const.ERR_OK,Utils.u2pstr(nickname),Utils.u2pstr(headimgurl),sex))
            GameDb.instance.loginWeChat(pid,nickname,headimgurl,sex,openid,unionid)
        else:
            logging.warn(u"pid = %d there is no client !!!!!!!",pid)
        logging.debug(u"######### End validate WeChat platform #########")
        pass

    def send(self,pid,wxcode):
        logging.debug(u"######### Start validate WeChat platform #########")
        logging.debug(u"WeChat send wxcode=%s",wxcode)
        data = u'appid=%s&secret=%s&code=%s&grant_type=%s' % (WeChatConfig.APP_ID,WeChatConfig.SECRET,wxcode,"authorization_code")
        logging.debug(u'send data:%s', data)
        agent = Agent(reactor)
        url = WeChatConfig.AUTH_URL.encode(WeChatConfig.ENCODING) + data.encode(WeChatConfig.ENCODING)
        logging.debug(u"WX url=%s",url)
        d = agent.request("GET",url,Headers({'Content-Type':['application/x-www-form-urlencoded']}),None)
        d.addCallback(self.cbRequest,pid,wxcode)


instance = WeChatGate()
if __name__ == '__main__':
    pass
